package org.kazuhiko.rpg.server.util;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.kazuhiko.rpg.server.model.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PlayerList
{
	private static final Logger logger = LoggerFactory.getLogger( PlayerList.class );
	
	private final int maximumPlayers; //No more no more
	
	private final Player[] players;
	
	private int size = 0;
	
	public PlayerList()
	{
		maximumPlayers = 64;
		players = new Player[maximumPlayers];
		size = 0;
	}
	
	public Collection<Player> getPlayers()
	{
		List<Player> playerList = new LinkedList<Player>();
		
		for( Player player : players )
		{
			if( player != null )
			{
				playerList.add( player );
			}
		}
		
		return Collections.unmodifiableCollection( playerList );
	}
	
	public boolean add( Player player )
	{
		for( int i = 0; i< players.length; i++ )
		{
			if( players[i] == null )
			{
				players[i] = player;
				player.setId( i );
				logger.trace( "Setting {} as id for {}", i, player );
				assert( player.getId() == i ); //Double check if we used the right id
				size++;
				return true;
			}
		}
		
		return false;
	}
	
	public void remove( Player player )
	{
		for( int i = 0; i < players.length; i++ )
		{
			if( player.equals( players[i] ) )
			{
				players[i] = null;
				size--;
			}
		}
		
		player.setId( -1 ); //Negative ID! remove this guy
	}
	
	public Player getPlayer( String name )
	{
		Player player = null;
		
		for( int i = 0; i < players.length && player == null; i++ )
		{
			if( players[i].getName().equals( name ) )
			{
				player = players[i];
			}
		}
		
		return player;
	}
	
	public Player getPlayer( int id )
	{
		Player player = null;
		
		for( int i = 0; i < players.length && player == null; i++ )
		{
			if( players[i].getId() == id )
			{
				player = players[i];
			}
		}
			
		return player;
	}
	
	public int size()
	{
		return size;
	}
	
	public boolean hasUsername( String username )
	{
		boolean found = false;
		
		for( int i = 0; i < players.length; i++ )
		{
			Player player = players[i];
			
			if( player != null && player.getName().equals( username ) )
			{
				found = true;
			}
		}
		
		return found;
	}
}
